<template>
  <div id="organization-index" v-loading="loading">
    <el-tabs v-model="editableTabsValue" @tab-remove="removeTab" @tab-click="clickTab">
      <el-tab-pane :name="defaultActiveName" label="组织架构">
        <el-row>
          <el-button-group style="margin-bottom: 7px;float: left;">
            <el-button size="mini" type="primary" v-export-excel-directive="exportExcelPar" v-has-permission="'OrganizationIndex.export'"
              icon="el-icon-download">导出</el-button>
            <el-button size="mini" type="primary" v-if="disableDeleteButton" @click="remove" v-has-permission="'OrganizationIndex.delete'"
              icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="primary" @click="initUserOrganizationRelation" v-has-permission="'OrganizationIndex.initUserOrganizationRelation'"
              icon="el-icon-refresh-left">刷新用户组织</el-button>
            <el-button size="mini" type="primary" v-if="disableAddAgentButton" @click="handleCommand('AddAgent')"
              v-has-permission="'OrganizationIndex.addagent'" icon="el-icon-plus">添加代理商</el-button>
            <el-button size="mini" type="primary" v-if="disableAddParentCompanyButton" @click="handleCommand('AddParentCompany')"
              v-has-permission="'OrganizationIndex.addParentCompany'" icon="el-icon-plus">添加总公司</el-button>
            <el-button size="mini" type="primary" v-if="disableAddBranchCompanyButton" @click="handleCommand('AddBranchCompany')"
              v-has-permission="'OrganizationIndex.addBranchCompany'" icon="el-icon-plus">添加分公司</el-button>
            <el-button size="mini" type="primary" v-if="disableAddProjectButton" @click="handleCommand('AddProject')"
              v-has-permission="'OrganizationIndex.addProject'" icon="el-icon-plus">添加项目</el-button>
            <el-button size="mini" type="primary" v-if="disableAddDepartmentButton" @click="handleCommand('AddDepartment')"
              v-has-permission="'OrganizationIndex.addDepartment'" icon="el-icon-plus">添加部门</el-button>
            <el-button size="mini" type="primary" v-if="disableAddRoleButton" @click="handleCommand('AddRole')"
              v-has-permission="'OrganizationIndex.addRole'" icon="el-icon-plus">添加岗位</el-button>
            <el-button size="mini" type="primary" v-if="disableAddUserButton" @click="handleCommand('AddUser')"
              v-has-permission="'OrganizationIndex.addUser'" icon="el-icon-plus">添加员工</el-button>
            <el-button size="mini" type="primary" v-if="disableSetFunctionPermissionsButton" @click="setFunctionPermissions"
              v-has-permission="'OrganizationIndex.setFunctionPermissions'" icon="el-icon-setting">权限设置</el-button>
          </el-button-group>
        </el-row>
        <el-container class="my-el-container">
          <el-aside class="my-el-aside">
            <el-form @submit.native.prevent>
              <el-input size="mini" v-model="ztreeSearchKey" @keyup.enter.native="onSearch">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </el-form>
            <ul id="tree" class="ztree"></ul>
          </el-aside>
          <el-main class="my-el-main">
            <el-divider v-if="selectedNode.type != ''">明细</i></el-divider>
            <div v-if="selectedNode.type == 'A101101' || selectedNode.type == 'A101104' || selectedNode.type == 'A101107'" class="my-detail">
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>公司名称:</label>
                </el-col>
                <el-col :span="5">
                  <el-tag size="mini">{{detailModel.name }}</el-tag>
                </el-col>
                <el-col :span="3">
                  <label>公司类型:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.typeLabel}}
                </el-col>
                <el-col :span="3">
                  <label>管理员账号:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.adminAccount}}
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>创建时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.createTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>创建人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.createrName ? detailModel.createrName : '/'}}
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>最后更新时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.modifyTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>更新人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.modifyName ? detailModel.modifyName : '/'}}
                </el-col>
              </el-row>
            </div>
            <div v-if="selectedNode.type == 'A101109'" class="my-detail">
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>项目名称:</label>
                </el-col>
                <el-col :span="5">
                  <el-tag size="mini">{{detailModel.name }}</el-tag>
                </el-col>
                <el-col :span="3">
                  <label>管理员账号:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.adminAccount}}
                </el-col>
                <el-col :span="3">
                  <label>项目地址:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.addr}}
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>创建时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.createTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>创建人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.createrName ? detailModel.createrName : '/'}}
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="3">
                  <label>最后更新时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.modifyTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>更新人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.modifyName ? detailModel.modifyName : '/'}}
                </el-col>
              </el-row>
            </div>
            <div v-if="selectedNode.type == 'A101111'" class="my-detail">
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>部门编码:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.code}}
                </el-col>
                <el-col :span="3">
                  <label>部门名称:</label>
                </el-col>
                <el-col :span="5">
                  <el-tag size="mini">{{detailModel.name }}</el-tag>
                </el-col>
                <el-col :span="5">
                  {{detailModel.adminAccount}}
                </el-col>
                <el-col :span="3">
                  <label>部门类型:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.typeLabel}}
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>创建时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.createTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>创建人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.createrName ? detailModel.createrName : '/'}}
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>最后更新时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.modifyTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>更新人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.modifyName ? detailModel.modifyName : '/'}}
                </el-col>
              </el-row>
            </div>
            <div v-if="selectedNode.type == 'A101113'" class="my-detail">
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>岗位编码:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.code}}
                </el-col>
                <el-col :span="3">
                  <label>岗位名称:</label>
                </el-col>
                <el-col :span="5">
                  <el-tag size="mini">{{detailModel.name }}</el-tag>
                </el-col>
                <el-col :span="3">
                  <label>岗位状态:</label>
                </el-col>
                <el-col :span="5">
                  <el-tag type="success" effect="dark" size="mini" v-if="detailModel.status == 'A100201'">
                    {{detailModel.statusLabel}}</el-tag>
                  <el-tag type="danger" effect="dark" size="mini" v-if="detailModel.status == 'A100202'">
                    {{detailModel.statusLabel}}</el-tag>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>创建时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.createTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>创建人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.createrName ? detailModel.createrName : '/'}}
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>最后更新时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.modifyTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>更新人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.modifyName ? detailModel.modifyName : '/'}}
                </el-col>
              </el-row>
            </div>
            <div v-if="selectedNode.type == 'A101115'" class="my-detail">
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>登录账号:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.loginName}}
                </el-col>
                <el-col :span="3">
                  <label>用户姓名:</label>
                </el-col>
                <el-col :span="5">
                  <el-tag size="mini">{{detailModel.realName }}</el-tag>
                </el-col>
                <el-col :span="3">
                  <label>用户状态:</label>
                </el-col>
                <el-col :span="5">
                  <el-tag type="success" effect="dark" size="mini" v-if="detailModel.status == 'A102901'">
                    {{detailModel.statusLabel}}</el-tag>
                  <el-tag type="danger" effect="dark" size="mini" v-if="detailModel.status == 'A102902'">
                    {{detailModel.statusLabel}}</el-tag>
                  <el-tag type="warning" effect="dark" size="mini" v-if="detailModel.status == 'A102903'">
                    {{detailModel.statusLabel}}</el-tag>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>性别:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.sexLabel ? detailModel.sexLabel : '/'}}
                </el-col>
                <el-col :span="3">
                  <label>用户类型:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.typeLabel}}
                </el-col>
                <el-col :span="3">
                  <label>邮箱地址:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.email ? detailModel.email : '/'}}
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>练习电话:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.mobilePhone ? detailModel.mobilePhone : '/'}}
                </el-col>
                <el-col :span="3">
                  <label>创建时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.createTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>创建人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.createrName ? detailModel.createrName : '/'}}
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="3">
                  <label>最后更新时间:</label>
                </el-col>
                <el-col :span="5">
                  <i class="el-icon-time"></i>
                  {{detailModel.modifyTime | formatDate('yyyy-MM-dd hh:mm:ss')}}
                </el-col>
                <el-col :span="3">
                  <label>更新人:</label>
                </el-col>
                <el-col :span="5">
                  {{detailModel.modifyName ? detailModel.modifyName : '/'}}
                </el-col>
              </el-row>
            </div>
            <el-table border size="mini" :row-class-name="tableRowClassName" :data="baseDto4user.lstDto">
              <el-table-column label="操作" width="80">
              </el-table-column>
              <el-table-column prop="loginName" label="登录账号" width="150">
              </el-table-column>
              <el-table-column label="姓名" width="180">
                <template slot-scope="scope">
                  <el-tag size="medium">{{scope.row.realName }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="mobilePhone" label="联系电话" width="150">
              </el-table-column>
              <el-table-column prop="typeLabel" label="用户类型" width="120">
              </el-table-column>
              <el-table-column prop="sexLabel" label="性别" width="80">
              </el-table-column>
              <el-table-column label="状态" width="80">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.status == 'A102901'" type="success" size="mini" effect="dark">{{scope.row.statusLabel}}</el-tag>
                  <el-tag v-if="scope.row.status == 'A102902'" type="danger" size="mini" effect="dark">{{scope.row.statusLabel}}</el-tag>
                  <el-tag v-if="scope.row.status == 'A102903'" type="warning" size="mini" effect="dark">{{scope.row.statusLabel}}</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination @size-change="pageSizeChange4user" @current-change="pageIndexChange4user" :current-page="searchModel4user.pageDto.pageNum"
              :page-sizes="searchModel4user.pageDto.pageSizes" :page-size="searchModel4user.pageDto.pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="baseDto4user.page.total">
            </el-pagination>
          </el-main>
        </el-container>
      </el-tab-pane>
      <el-tab-pane v-for="(item) in editableTabs" :key="item.key" :label="item.label" :name="item.name" closable>
        <company-create v-if="item.key == 'AddCompany'" v-bind:selectedNode="selectedNode" v-on:addNode="addNode"></company-create>
        <project-create v-if="item.key == 'AddProject'" v-bind:selectedNode="selectedNode" v-on:addNode="addNode"></project-create>
        <department-create v-if="item.key == 'AddDepartment'" v-bind:selectedNode="selectedNode" v-on:addNode="addNode"></department-create>
        <role-create v-if="item.key == 'AddRole'" v-bind:selectedNode="selectedNode" v-on:addNode="addNode"></role-create>
        <user-add v-if="item.key == 'AddUser'" v-bind:selectedNode="selectedNode" v-on:addNode="addNode"></user-add>
        <function-tree v-if="item.key == 'SetFunctionPermissions'" v-bind:selectedNode="selectedNode"></function-tree>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import Vue from 'vue'
import '../../../../static/zTree_v3.5.27/js/jquery.ztree.core.js'
import '../../../../static/zTree_v3.5.27/js/jquery.ztree.excheck.js'
import '../../../../static/zTree_v3.5.27/js/jquery.ztree.exedit.js'
import UserAdd from './user-add'
import FunctionTree from '../../../common/component/function-tree-role'
import CompanyCreate from './company-create'
import ProjectCreate from './project-create'
import DepartmentCreate from './department-create'
import RoleCreate from './role-create'

export default {
  name: 'organization-list',
  components: {
    RoleCreate,
    DepartmentCreate,
    ProjectCreate,
    CompanyCreate,
    FunctionTree,
    UserAdd
  },
  data () {
    return {
      loading: true,
      baseDto4user: {
        page: {
          total: 0
        }
      },
      setting: {
        view: {
          showLine: true,
          fontCss: function (treeId, treeNode) {
            return (treeNode.highlight) ? {
              color: '#A60000',
              'font-weight': 'bold'
            } : {
              'font-weight': 'normal'
            }
          }
        },
        data: {
          simpleData: {
            enable: true
          }
        },
        callback: {
          beforeClick: (treeId, treeNode, clickFlag) => {
            this.selectedNode = treeNode
            this.searchModel.pid = treeNode.id
            this.searchModel.type = treeNode.type

            this.switchButtonAvailableStatus(treeNode.type)
            this.getDetailById()
            this.search4user()
          }
        }
      },
      searchModel: {
        id: '',
        pid: '-1',
        type: '',
        relationId: '',
        name: ''
      },
      searchModel4user: {
        pageDto: {
          pageSize: 10,
          pageNum: 1,
          pageSizes: [10, 20, 30, 100]
        },
        agentId: null,
        parentCompanyId: null,
        branchCompanyId: null,
        projectId: null,
        departmentId: null,
        roleId: null
      },
      detailModel: {},
      ztreeSearchKey: null,
      disableAddAgentButton: false,
      disableAddParentCompanyButton: false,
      disableAddBranchCompanyButton: false,
      disableAddDepartmentButton: false,
      disableAddProjectButton: false,
      disableAddRoleButton: false,
      disableAddUserButton: false,
      disableDeleteButton: false,
      disableSetFunctionPermissionsButton: false,
      selectedNode: {
        id: '',
        pid: '-1',
        name: '',
        type: '',
        relationId: ''
      },
      searchHitZNodes: [],
      selectedModel: {
        type: ''
      },
      exportExcelPar: {
        fileType: 'xls',
        xmlName: 'admin_organization',
        moduleName: 'organization',
		server: Vue.$adminServerURL
      },
      defaultActiveName: 'OrganizationList',
      editableTabsValue: 'OrganizationList',
      editableTabs: [],
      tabIndex: 2
    }
  },
  created: function () {
    this.buildTree()
  },
  async mounted () {},
  methods: {
    tableRowClassName ({
      row,
      rowIndex
    }) {
      if ((rowIndex + 1) % 2 === 1) {
        return 'success-row'
      }
      return ''
    },
    buildTree: function () {
      Vue.$ajax({
        method: 'post',
        url: Vue.$adminServerURL + '/web/v1/OrganizationController/buildTree',
        data: this.searchModel
      }).then(res => {
        this.loading = false
        if (res.data.flag === 'SUCCESS') {
          let zNodes = JSON.parse(res.data.obj.leftTree)

          // eslint-disable-next-line no-undef
          let treeObj = $.fn.zTree.init($('#tree'), this.setting, zNodes)

          if (this.selectedNode != null && this.selectedNode.pid != null && this.selectedNode.id !== '') {
            this.expandParentNodes(this.selectedNode.children[0], treeObj)
            // eslint-disable-next-line no-undef
            $('#' + this.selectedNode.tId + '_a').click()
          } else {
            let nodes = treeObj.getNodes()
            if (nodes.length > 0) {
              // eslint-disable-next-line no-undef
              $('#tree_1_a').click()
            }
          }
        } else {
          if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          }
        }
      })
    },

    getDetailById: function () {
      Vue.$ajax({
        method: 'post',
        url: Vue.$adminServerURL + '/web/v1/OrganizationController/getDetailById?id=' + this.selectedNode.id
      }).then(res => {
        if (res.data.flag !== 'SUCCESS') {
          if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          }
        } else {
          this.detailModel = res.data.obj
        }
      })
    },
    handleSelectionChange: function (val) {

    },
    listPage4user: function () {
      if (this.selectedNode.type === 'A101101') {
        this.searchModel4user.agentId = this.selectedNode.relationId
        this.searchModel4user.parentCompanyId = null
        this.searchModel4user.branchCompanyId = null
        this.searchModel4user.projectId = null
        this.searchModel4user.departmentId = null
        this.searchModel4user.roleId = null
      } else if (this.selectedNode.type === 'A101104') {
        this.searchModel4user.parentCompanyId = this.selectedNode.relationId
        this.searchModel4user.agentId = null
        this.searchModel4user.branchCompanyId = null
        this.searchModel4user.projectId = null
        this.searchModel4user.departmentId = null
        this.searchModel4user.roleId = null
      } else if (this.selectedNode.type === 'A101107') {
        this.searchModel4user.branchCompanyId = this.selectedNode.relationId
        this.searchModel4user.agentId = null
        this.searchModel4user.parentCompanyId = null
        this.searchModel4user.projectId = null
        this.searchModel4user.departmentId = null
        this.searchModel4user.roleId = null
      } else if (this.selectedNode.type === 'A101109') {
        this.searchModel4user.projectId = this.selectedNode.relationId
        this.searchModel4user.agentId = null
        this.searchModel4user.parentCompanyId = null
        this.searchModel4user.branchCompanyId = null
        this.searchModel4user.departmentId = null
        this.searchModel4user.roleId = null
      } else if (this.selectedNode.type === 'A101111') {
        this.searchModel4user.departmentId = this.selectedNode.relationId
        this.searchModel4user.agentId = null
        this.searchModel4user.parentCompanyId = null
        this.searchModel4user.branchCompanyId = null
        this.searchModel4user.projectId = null
        this.searchModel4user.roleId = null
      } else if (this.selectedNode.type === 'A101113') {
        this.searchModel4user.roleId = this.selectedNode.relationId
        this.searchModel4user.agentId = null
        this.searchModel4user.parentCompanyId = null
        this.searchModel4user.branchCompanyId = null
        this.searchModel4user.projectId = null
        this.searchModel4user.departmentId = null
      } else if (this.selectedNode.type === 'A101115') {
        this.loading = false
        return
      } else {
        this.searchModel4user.agentId = null
        this.searchModel4user.parentCompanyId = null
        this.searchModel4user.branchCompanyId = null
        this.searchModel4user.projectId = null
        this.searchModel4user.departmentId = null
        this.searchModel4user.roleId = null
      }
      Vue.$ajax({
        method: 'post',
        url: Vue.$adminServerURL + '/web/v1/UserController/listPageByParentOrganization',
        data: this.searchModel4user
      }).then(res => {
        this.loading = false
        if (res.data.flag === 'SUCCESS') {
          this.baseDto4user = res.data
        } else {
          if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          }
        }
      })
    },
    pageSizeChange4user: function (e) {
      this.searchModel4user.pageDto.pageSize = e
      this.listPage4user()
    },
    pageIndexChange4user: function (e) {
      this.searchModel4user.pageDto.pageNum = e
      this.listPage4user()
    },
    search4user: function () {
       this.loading = true
      this.searchModel4user.pageDto.pageNum = 1
      this.listPage4user()
    },

    // 树搜索
    onSearch: function ($even) {
      let searchKeyWord = ''
      if (Vue.$isNullOrIsBlankOrIsUndefined($even) || Vue.$isNullOrIsBlankOrIsUndefined($even.target)) {
        searchKeyWord = this.ztreeSearchKey
      } else {
        searchKeyWord = $even.target.value
      }
      if (!Vue.$isNullOrIsBlankOrIsUndefined(searchKeyWord)) {
        this.updateHitZNodesStyle(false)
        // eslint-disable-next-line no-undef
        let treeObj = $.fn.zTree.getZTreeObj('tree')
        this.searchHitZNodes = treeObj.getNodesByParam('id', searchKeyWord, null)
        if (this.searchHitZNodes == null) {
          this.searchHitZNodes = treeObj.getNodesByParamFuzzy('name', searchKeyWord, null)
        }
        if (this.searchHitZNodes != null) {
          this.updateHitZNodesStyle(true)

          /**
             * 展开搜索到的节点
             */
          for (let i = 0; i < this.searchHitZNodes.length; i++) {
            this.expandParentNodes(this.searchHitZNodes[i], treeObj)
          }
        }
      }
      this.ztreeSearchKey = null
    },

    // 展开父节点
    expandParentNodes: function (treeNode, treeObj) {
      let parentNode = treeNode.getParentNode()
      if (parentNode != null) {
        treeObj.expandNode(parentNode, true, false, true)
      }
    },

    // 更新命中节点样式
    updateHitZNodesStyle: function (highlight) {
      // eslint-disable-next-line no-undef
      let treeObj = $.fn.zTree.getZTreeObj('tree')
      let nodeLength = this.searchHitZNodes.length
      for (let i = 0; i < nodeLength; i++) {
        this.searchHitZNodes[i].highlight = highlight
        treeObj.updateNode(this.searchHitZNodes[i])
      }
    },

    /**
       * 切换按钮可用状态
       * @param type
       */
    switchButtonAvailableStatus: function (type) {
      if (type === '') { // 选中树的[根]节点，则启用添加代理商按钮
        this.disableAddAgentButton = true

        this.disableAddParentCompanyButton = false
        this.disableAddBranchCompanyButton = false
        this.disableDeleteButton = false
        this.disableAddProjectButton = false
        this.disableAddDepartmentButton = false
        this.disableAddRoleButton = false
        this.disableAddUserButton = false
        this.disableSetFunctionPermissionsButton = false
      } else if (type === 'A101101') { // 选中树的[代理商]节点，则启用添加总公司、设置管理员和移出组织按钮
        this.disableAddParentCompanyButton = true
        this.disableDeleteButton = true

        this.disableAddAgentButton = false
        this.disableAddBranchCompanyButton = false
        this.disableAddProjectButton = false
        this.disableAddDepartmentButton = false
        this.disableAddRoleButton = false
        this.disableAddUserButton = false
        this.disableSetFunctionPermissionsButton = false
      } else if (type === 'A101104') { // 选中树的[总公司]节点，则启用添加分公司、设置管理员和移出组织按钮
        this.disableAddBranchCompanyButton = true
        this.disableDeleteButton = true

        this.disableAddAgentButton = false
        this.disableAddParentCompanyButton = false
        this.disableAddProjectButton = false
        this.disableAddDepartmentButton = false
        this.disableAddRoleButton = false
        this.disableAddUserButton = false
        this.disableSetFunctionPermissionsButton = false
      } else if (type === 'A101107') { // 选中树的[分公司]节点，则启用添加部门、设置管理员和移出组织按钮
        this.disableDeleteButton = true

        this.disableAddAgentButton = false
        this.disableAddParentCompanyButton = false
        this.disableAddBranchCompanyButton = false
        this.disableAddProjectButton = false
        this.disableAddDepartmentButton = false
        this.disableAddRoleButton = false
        this.disableAddUserButton = false
        this.disableSetFunctionPermissionsButton = false
      } else if (type === 'A101109') { // 选中树的[项目]节点，则启用添加部门按钮和移出组织按钮
        this.disableAddDepartmentButton = true
        this.disableDeleteButton = true

        this.disableAddAgentButton = false
        this.disableAddParentCompanyButton = false
        this.disableAddBranchCompanyButton = false
        this.disableAddProjectButton = false
        this.disableAddRoleButton = false
        this.disableAddUserButton = false
        this.disableSetFunctionPermissionsButton = false
      } else if (type === 'A101111') { // 选中树的部门点：部门类型为【项目部门】则启用添加项目和移出组织按钮，部门类型为【职能部门】则启用添加岗位和移出组织按钮
        Vue.$ajax({
          method: 'post',
          url: Vue.$adminServerURL + '/web/v1/OrganizationController/findRelationBeanByRelationId?type=' + type +
              '&relationId=' + this.selectedNode.relationId
        }).then(res => {
          if (res.data.flag === 'SUCCESS') {
            let departmentType = res.data.obj.type
            if (departmentType === 'A102703') { // 项目部门
              this.disableAddProjectButton = true
              this.disableDeleteButton = true

              this.disableAddAgentButton = false
              this.disableAddParentCompanyButton = false
              this.disableAddBranchCompanyButton = false
              this.disableAddDepartmentButton = false
              this.disableAddRoleButton = false
              this.disableAddUserButton = false
              this.disableSetFunctionPermissionsButton = false
            } else {
              this.disableAddRoleButton = true
              this.disableDeleteButton = true

              this.disableAddAgentButton = false
              this.disableAddParentCompanyButton = false
              this.disableAddBranchCompanyButton = false
              this.disableAddProjectButton = false
              this.disableAddDepartmentButton = false
              this.disableAddUserButton = false
              this.disableSetFunctionPermissionsButton = false
            }
          } else {
            if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
              this.$message({
                message: res.data.message,
                type: 'warning'
              })
            }
          }
        })
      } else if (type === 'A101113') { // 选中树的岗位节点，则启用添加用户按钮和移出组织按钮
        this.disableAddUserButton = true
        this.disableDeleteButton = true
        this.disableSetFunctionPermissionsButton = true

        this.disableAddAgentButton = false
        this.disableAddParentCompanyButton = false
        this.disableAddBranchCompanyButton = false
        this.disableAddProjectButton = false
        this.disableAddDepartmentButton = false
        this.disableAddRoleButton = false
      } else if (type === 'A101115') { // 选中树的用户节点，则只启用移出组织按钮
        this.disableDeleteButton = true

        this.disableAddAgentButton = false
        this.disableAddParentCompanyButton = false
        this.disableAddBranchCompanyButton = false
        this.disableAddProjectButton = false
        this.disableAddDepartmentButton = false
        this.disableAddRoleButton = false
        this.disableAddUserButton = false
        this.disableSetFunctionPermissionsButton = false
      }
    },
    initUserOrganizationRelation: function () {
      Vue.$ajax({
        method: 'post',
        url: Vue.$adminServerURL + '/web/v1/SysUserOrganization/init'
      }).then(res => {
        if (res.data.flag === 'SUCCESS') {
          this.$message({
            message: res.data.message,
            type: 'success'
          })
        } else {
          if (!Vue.$isNullOrIsBlankOrIsUndefined(res.data.message)) {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          }
        }
      })
    },
    handleCommand (command) {
      if (command === 'AddAgent') {
        this.addTab('添加代理商', 'AddAgent', 'AddCompany')
      } else if (command === 'AddParentCompany') {
        this.addTab('添加总公司', 'addParentCompany', 'AddCompany')
      } else if (command === 'AddBranchCompany') {
        this.addTab('添加分公司', 'AddBranchCompany', 'AddCompany')
      } else if (command === 'AddDepartment') {
        this.addTab('添加部门', 'AddDepartment', 'AddDepartment')
      } else if (command === 'AddProject') {
        this.addTab('添加项目', 'AddProject', 'AddProject')
      } else if (command === 'AddRole') {
        this.addTab('添加岗位', 'AddRole', 'AddRole')
      } else if (command === 'AddUser') {
        this.addTab('添加用户', 'AddUser', 'AddUser')
      }
    },
    setFunctionPermissions: function () {
      this.addTab('设置功能权限', 'SetFunctionPermissions', 'SetFunctionPermissions')
      this.selectedModel = this.selectedNode
    },
    remove: function () {
      let that = this
      if (Vue.$isNullOrIsBlankOrIsUndefined(this.selectedNode) || Vue.$isNullOrIsBlankOrIsUndefined(this.selectedNode
        .id)) {
        this.$message({
          message: '请选择数据',
          type: 'warning'
        })
        return
      }

      let msg = ''
      if (this.selectedNode.type === 'A101101') { // 代理商
        msg = '此操作会删除代理商以及该代理商下所有相关数据，您确定要继续吗'
      } else {
        msg = '您确定删除该记录吗'
      }

      this.$confirm(msg, '询问', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        Vue.$ajax({
          method: 'delete',
          url: Vue.$adminServerURL + '/web/v1/OrganizationController/' + that.selectedNode.id
        }).then(res => {
          this.loading = false
          if (res.data.flag !== 'SUCCESS') {
            this.$message({
              message: res.data.message,
              type: 'warning'
            })
          } else {
            this.$message({
              message: res.data.message,
              type: 'success'
            })
            this.removeNode()
          }
        })
      }).catch(() => {})
    },
    removeNode: function () {
      // eslint-disable-next-line no-undef
      let treeObj = $.fn.zTree.getZTreeObj('tree')

      treeObj.removeNode(this.selectedNode)
    },
    addNode: function (newNode) {
      this.removeTab(this.editableTabsValue)
      this.buildTree()

      let that = this
      setTimeout(() => {
        that.ztreeSearchKey = newNode.id
        that.onSearch(null)
      }, 1000)
    },
    addTab: function (label, name, key) {
      let ele = {
        label: label,
        name: name,
        key: key
      }
      let flag = false

      for (let i = 0; i < this.editableTabs.length; i++) {
        let var1 = this.editableTabs[i]
        if (var1.key === key) {
          flag = true
          break
        }
      }

      if (!flag) {
        this.editableTabs.push(ele)
      }
      this.editableTabsValue = name
    },
    removeTab: function (targetName) {
      let tabs = this.editableTabs
      let activeName = this.editableTabsValue
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
            } else {
              activeName = this.defaultActiveName
              // eslint-disable-next-line no-undef
              $('#' + this.selectedNode.tId + '_a').click()
            }
          }
        })
      }
      this.editableTabsValue = activeName
      this.editableTabs = tabs.filter(tab => tab.name !== targetName)
    },
    clickTab: function (tab) {
      if (tab.name === this.defaultActiveName) {
        // eslint-disable-next-line no-undef
        $('#' + this.selectedNode.tId + '_a').click()
      }
    }
  }
}
</script>
<style>
  @import '../../../../static/zTree_v3.5.27/css/zTreeStyle.css';

  #organization-index .my-el-container {
    border: 1px solid #eee;
  }

  #organization-index .my-el-aside {
    overflow-y: auto;
    border-right: 1px solid #eee;
  }

  #organization-index .my-el-main {
    padding-top: 0px;
    height: 73vh;
  }
</style>
